﻿using System.Linq;
using System.Reflection;
using PersonaLibrary.Data;

namespace PersonaLibrary.ViewModel.ExcelViewModel
{
    internal class ImportNote : BaseExcelVM
    {
        private readonly LinqToDbDataContext context = new LinqToDbDataContext();

        protected override void CommitOperation()
        {
            Note note;
            if (context.Notes.Any(x => x.Name == OpenedWorksheet.Name))
                note = context.Notes.Single(x => x.Name == OpenedWorksheet.Name);
            else
            {
                note = new Note {Name = OpenedWorksheet.Name};
                context.Notes.InsertOnSubmit(note);
                context.SubmitChanges();
            }
            
            var range = OpenedWorksheet.Range[Offset, Missing.Value];
            range = range.Resize[OpenedWorksheet.UsedRange.Rows.Count, 1];
            object[,] values = range.Value2;

            for (int i = 1; i <= values.Length; i++)
            {
                if(values[i,1] == null) continue;

                string employeeString = values[i, 1].ToString();
                string[] str = employeeString.Split(" ".ToCharArray());
                if (context.Employees.Any(
                        x => str.Contains(x.Surname) && str.Contains(x.Name) && str.Contains(x.Patronymic)))
                {
                    Employee emp = context.Employees.Single(
                        x => str.Contains(x.Surname) && str.Contains(x.Name) && str.Contains(x.Patronymic));

                    if (!context.EmployeeNoteLinks.Any(x => x.EmployeeId == emp.Id && x.NoteId == note.Id))
                    {
                        EmployeeNoteLink link = new EmployeeNoteLink {EmployeeId = emp.Id, NoteId = note.Id};
                        context.EmployeeNoteLinks.InsertOnSubmit(link);
                        context.SubmitChanges();
                    }
                }
            }
            base.CommitOperation();
        }
    }
}
